package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.TemporalUnit;
import java.util.List;

/**
 * @author wjh
 * @create 2023-07-11
 */
@Component
@Slf4j
public class OrderTask {

    @Resource
    private OrdersMapper ordersMapper;

    /**
     * 每分钟触发一次检查超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder(){
        LocalDateTime now = LocalDateTime.now();
        log.info("定时处理超时订单：{}", now);
        LocalDateTime time = now.plusMinutes(-15);
        List<Orders> ordersList = ordersMapper.selectTimeOutOrder(Orders.PENDING_PAYMENT,time);
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(now);
                ordersMapper.updateById(orders);
            }
        }
    }

    /**
     * 每5分钟处理派送时长为2.5小时以上的订单
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void processDeliverOrder(){
        LocalDateTime now = LocalDateTime.now();
        log.info("定时一直是配送中的订单：{}", now);
        LocalDateTime time = now.plusMinutes(-150);
        List<Orders> ordersList = ordersMapper.selectTimeOutOrder(Orders.DELIVERY_IN_PROGRESS,time);
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                ordersMapper.updateById(orders);
            }
        }
    }
}
